package com.lanyan.common.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PosterUtil {

	public static void main(String[] args) throws IOException {
		try {
			File file = new File("e:/test/index.png");
			BufferedImage image = ImageIO.read(file);

			int width = image.getWidth();
			int height = image.getHeight();
			int indexX = 0;
			int indexY = 0;


			System.out.println("Image Width: " + width);
			System.out.println("Image Height: " + height);

			// 创建 Graphics2D 对象
			Graphics2D g2 = image.createGraphics();
			Color color = g2.getColor();
			g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1));

			g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // 消除画图锯齿
			g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); // 消除文字锯齿
			g2.setColor(color);
			// 在这里可以进行其他操作，如绘制形状、添加文本等
			//放入主图
			Color squareColor = new Color(255, 0, 0, 255);
			g2.setColor(squareColor);
			indexY += 30;
			indexX = 30;
			indexY +=(642 + 50);

			g2.setFont(new Font("PingFang SC-Bold", Font.PLAIN, 40));
			g2.setColor(Color.BLACK);
			//一个汉字42.5
			String proName = "SK水乳护肤品套装正品美白淡斑控油补水保湿抗皱化妆品";//26个字
			String[] split = proName.split("");
			int lineSize = 0;
			List<String> lines = new ArrayList<>();
			StringBuffer sb = new StringBuffer();
			for (String s : split) {
				if (s.matches("[a-zA-Z]+")){
					lineSize += 21.2;
				}else {
					lineSize += 42.5;
				}
				sb.append(s);
				if (lineSize >= 640){
					lines.add(sb.toString());
					sb = new StringBuffer();
					lineSize = 0;
				}
			}
			lines.add(sb.toString());
			for (String line : lines) {
				g2.drawString(line, 30, indexY);
				indexY += 50;
			}


			g2.fillRoundRect(30, 30, 642, 642, 20, 20);
			g2.clip(new RoundRectangle2D.Double(30, 30, 642, 642, 20, 20));

			// 绘制商品主图
			g2.drawImage(ImageIO.read(new File("e:/test/pro.jpg")),
					30,
					30,
					642,
					642,
					null);
			// 释放 Graphics2D 对象
			g2.dispose();
			String outputFileName = System.currentTimeMillis()+".png";
			File outputFile = new File("e:/test/"+outputFileName);
			ImageIO.write(image, "PNG", outputFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
